//
//  ODbManager.m
//  OFootball
//
//  Created by 上官千城 on 15/9/22.
//  Copyright (c) 2015年 上官千城. All rights reserved.
//

#import "ODbManager.h"
#import "OFileManager.h"

@implementation ODbManager


-(instancetype) initWithDomain:(NSString*)domainName
{
    self = [super init];
    if (self) {
        _domainName = domainName;
        return self;
    }
    return nil;
}

static NSMutableDictionary* dic = nil;

+(ODbManager*) getDomainManager:(NSString *)domainName
{
    return [dic objectForKey:domainName];
}



+(void)initializeDbManager:(NSArray*)domainNames
{
    if (dic) {
        return;
    }
    
    dic = [NSMutableDictionary dictionary];
    for (NSString* domainName in domainNames) {
        if (![OFileManager isDirExistInDocument:domainName]) {
            [OFileManager createDirInDocument:domainName];
        }
        ODbManager* manager = [[ODbManager alloc] initWithDomain:domainName];
        [dic setValue:manager forKey:domainName];
    }
   
}

-(NSString*) getFileName:(NSString*)aKey;
{
    NSString* fileName = [aKey stringByAppendingString:@".bin"];
    
    NSString* documentPath = [OFileManager getDocumentPath];
    
    NSString *path = [documentPath stringByAppendingPathComponent:_domainName];
    fileName = [path stringByAppendingPathComponent:fileName];
    
    return fileName;
}

-(BOOL) setObject:(NSObject *)objc forKey:(NSString *)aKey
{
    NSString* fileName = [self getFileName:aKey];
    return [NSKeyedArchiver archiveRootObject:objc toFile:fileName];
}

-(NSObject*) getObject:(NSString *)aKey
{
    NSString* fileName = [self getFileName:aKey];
    return [NSKeyedUnarchiver unarchiveObjectWithFile:fileName];
}

-(BOOL) deleteObject:(NSString*)aKey
{
    NSString* fileName = [self getFileName:aKey];
    return [OFileManager deleteFile:fileName];
}

@end
